package com.example.DBConfig;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;

/**
 *
 * Created by tony on 2017/7/26.
 */
@Configuration
@MapperScan(basePackages = "com.example.mapper.crm", sqlSessionTemplateRef  = "crmSqlSessionTemplate")
public class CrmDataSourceConfig {
    //crm数据库连接器
    @Bean(name="crmDataSource")
    @Qualifier("crmDataSource")
    @ConfigurationProperties(prefix="spring.datasource.crm")
    public DataSource crmDataSource() {
        System.out.println("--------------------crmDataSource build ---------------------");
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "crmSessionFactory")
    @Primary
    public SqlSessionFactory testSqlSessionFactory(@Qualifier("crmDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mappers/crm/*.xml"));
        return bean.getObject();
    }
    @Bean(name = "crmTransactionManager")
    @Primary
    public DataSourceTransactionManager testTransactionManager(@Qualifier("crmDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "crmSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("crmSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
